/**********************************************************************************************************************
 * SplendidCRM is a Customer Relationship Management program created by SplendidCRM Software, Inc. 
 * Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU Affero General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with this program. 
 * If not, see <http://www.gnu.org/licenses/>. 
 * 
 * You can contact SplendidCRM Software, Inc. at email address support@splendidcrm.com. 
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3, 
 * the Appropriate Legal Notices must display the following words on all interactive user interfaces: 
 * "Copyright (C) 2005-2011 SplendidCRM Software, Inc. All rights reserved."
 *********************************************************************************************************************/
using System;
using System.Data;
using System.Data.Common;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

namespace SplendidCRM.Campaigns
{
	/// <summary>
	/// Summary description for Default.
	/// </summary>
    public partial class AssignTeamContactReport : SplendidPage
	{
	    public Guid TransactionId { 
            get
            {
                return Request.QueryString["TransactionId"] != null ? Sql.ToGuid(Request.QueryString["TransactionId"]) : Guid.Empty;
            }
	    }

        public Guid RedirectId
        {
            get
            {
                return Request.QueryString["RedirectId"] != null ? Sql.ToGuid(Request.QueryString["RedirectId"]) : Guid.Empty;
            }
        }

		protected void Page_Load(object sender, System.EventArgs e)
		{
            if (!Page.IsPostBack)
            {
                var tbl = GetAsignTeamContact();
                grdAssignationReview.DataSource = tbl;
                grdAssignationReview.DataBind();
            }
		}

        private DataTable GetAsignTeamContact()
        {
            if (TransactionId == Guid.Empty) return null;

            var dbf = DbProviderFactories.GetFactory();
            using (var con = dbf.CreateConnection())
            {
                var cmdSelect = con.CreateCommand();
                cmdSelect.CommandType = CommandType.Text;
                cmdSelect.CommandText =
@" SELECT tca.ID, c.LAST_NAME 'CONTACT_NAME', t.NAME 'TEAM_NAME' 
   FROM dbo.TEAMS_CONTACT_ASSIGNATION tca
   JOIN dbo.CAMPAIGNS_CONTACTS cc on cc.ID = tca.CAMPAIGN_CONTACT_ID
   JOIN dbo.CONTACTS c on cc.CONTACT_ID = c.ID
   JOIN dbo.TEAMS t on t.ID = tca.TEAM_ID
   WHERE tca.TRANSACTION_ID = @TRANSACTION_ID
   AND tca.REPLACE_TRANSACTION_ID IS NULL 
   ORDER BY t.NAME, c.LAST_NAME ";
                Sql.AddParameter(cmdSelect, "@TRANSACTION_ID", TransactionId);
                IDbDataAdapter da = dbf.CreateDataAdapter();
                da.SelectCommand = cmdSelect;
                var ds = new DataSet();
                da.Fill(ds);

                //Clear team name after first meet
                var preTeamName = "";
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var teamName = row["TEAM_NAME"].ToString();
                    if (teamName.Equals(preTeamName)) {
                        row["TEAM_NAME"] = "";
                    } else {
                        preTeamName = teamName;
                    }
                }
                return ds.Tables[0];
            }
        }

        protected void cltOK_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("view.aspx?id=" + RedirectId);
        }

        protected void cltRollBack_OnClick(object sender, EventArgs e)
        {
            var result = RollBackAssignationTransaction();
            ScriptManager.RegisterStartupScript(this, typeof (Page), "script",
                                                result ? "alert('Rollback success!'); window.location='view.aspx?id=" + RedirectId + "';" : 
                                                "alert('Rollback failed!'); window.location='view.aspx?id=" + RedirectId + "';", true);
        }

	    private bool RollBackAssignationTransaction()
	    {
            try
            {
                var dbf = DbProviderFactories.GetFactory();
                using (var con = dbf.CreateConnection())
                {
                    con.Open();
                    var cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "spRollBackTeamContactAssignation";
                    Sql.AddParameter(cmd, "TRANSACTION_ID", TransactionId);

                    cmd.ExecuteNonQuery();

                    return true;
                }
            }
            catch (Exception ex)
            {
                Debugger.Break();
                return false;
            }
	    }
	}
}


